import { Injectable } from "@angular/core";
import { Subject } from "../../../../node_modules/rxjs";
import { HttpRequest } from "@angular/common/http";
import { StorageService } from "./storage.service";

@Injectable()
export class RefreshTokenService {
    public processing: boolean = false;
    public storage: Subject<any> = new Subject<any>();

    public publish(value: any) {
        this.storage.next(value);
    }

    public allowedCalls(url: string): boolean {
        return url.endsWith('auth/token') || url.endsWith('forgotPassword') || url.endsWith('setPassword');
    }

    public isAuthorized(): boolean {
        return localStorage.getItem('sust:a') != undefined;
    }

    public tokenExpired() {
        let now = new Date();
        let auth = StorageService.get().authData;
        let expires = new Date(auth.loginTime);
        expires.setSeconds(expires.getSeconds() + auth.expires_in);
        return now > expires;
    }

    public setAuthHeader(request: HttpRequest<any>): HttpRequest<any> {
        let auth = StorageService.get().authData;
        return request.clone({ setHeaders: { Authorization: `Bearer ${auth.access_token}` } });
    }
}